import os
import configparser
from pathlib import Path

DEFAULT_CONFIG = {
    'sys': {
        'server_file': 'login.xlsx',
        'develop_mode': '0',
        'develop_password': '',
        'batch_execute': '1'
    },
    'upload': {
        'default_files': '',
        'default_remote_dir': '/tmp'
    },
    'download': {
        'default_files': '',
        'default_save_path': ''
    },
    'deploy': {
        'configure_hostname': '1',
        'configure_hosts': '1',
        'configure_dns': '1',
        'sync_time': '1',
        'load_image': '0',
        'register_node': '0',
        'network_interface': 'eth0'
    },
    'ssh_tunnel': {
        'enable': '0',
        'jump_host': '',
        'username': '',
        'password': ''
    }
}


class ConfigManager:
    def __init__(self, config_file='config.ini'):
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self.load_config()

    def load_config(self):
        """加载配置文件，如果不存在则创建默认配置"""
        if not os.path.exists(self.config_file):
            self.create_default_config()

        self.config.read(self.config_file)

        # 检查是否有缺失的配置项
        for section, options in DEFAULT_CONFIG.items():
            if not self.config.has_section(section):
                self.config.add_section(section)
            for key, value in options.items():
                if not self.config.has_option(section, key):
                    self.config.set(section, key, value)

        self.save_config()

    def create_default_config(self):
        """创建默认配置文件"""
        for section, options in DEFAULT_CONFIG.items():
            self.config.add_section(section)
            for key, value in options.items():
                self.config.set(section, key, value)
        self.save_config()

    def save_config(self):
        """保存配置文件"""
        with open(self.config_file, 'w') as f:
            self.config.write(f)

    def get(self, section, option, default=None):
        """获取配置值"""
        try:
            return self.config.get(section, option)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return default

    def getboolean(self, section, option, default=False):
        """获取布尔型配置值"""
        try:
            return self.config.getboolean(section, option)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return default

    def set(self, section, option, value):
        """设置配置值"""
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, option, str(value))
        self.save_config() 